package host.skiree.nettydemo.netty.introduction.c3;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @author gcl
 * @date 2022/9/8 14:01
 */
@Slf4j
public class EventLoopServer {
    public static void main(String[] args) {
        // 细分2: 创建一个独立的EventLoopGroup 用于处理耗时的handler 也是与SocketChannel一一绑定的
        EventLoopGroup eventLoopGroup = new DefaultEventLoopGroup();
      new ServerBootstrap()
              // boss 处理 work
              // 细分1 : boss 只处理ServerSocketChannel的accept事件  work 只负责SocketChannel的读写
              .group(new NioEventLoopGroup(1), new NioEventLoopGroup(2))
              .channel(NioServerSocketChannel.class)
              .childHandler(new ChannelInitializer<NioSocketChannel>() {
                  @Override
                  protected void initChannel(NioSocketChannel ch) throws Exception {
                      ch.pipeline().addLast("handler1",new ChannelInboundHandlerAdapter(){
                          @Override
                          public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                              ByteBuf byteBuf = (ByteBuf) msg;
                              log.debug(byteBuf.toString(Charset.defaultCharset()));
                              ctx.fireChannelRead(msg); // 让消息传递到下一个handler
                          }
                      }).addLast(eventLoopGroup,"handler2",new ChannelInboundHandlerAdapter(){
                          @Override
                          public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                              ByteBuf byteBuf = (ByteBuf) msg;
                              log.debug(byteBuf.toString(Charset.defaultCharset()));
                          }
                      });
                  }
              })
              .bind(new InetSocketAddress(8080));
    }
}
